#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from project.flasky import db
from project.define import db_logger


DataName = "车场信息"
TableName = "app_carpark_setting"


class CarParkSetting(db.Model):
    """
    车场信息
    """
    __tablename__ = TableName
    # 车场名称
    Name = db.Column(db.String(64), primary_key=True, nullable=False)
    # 品牌名称
    Brand = db.Column(db.String(16))
    # 管理名称
    Company = db.Column(db.String(64))
    # 公司地址
    Address = db.Column(db.String(128))
    # 公司电话
    Phone = db.Column(db.String(16))
    # 车场模式:standard test
    Model = db.Column(db.String(16))
        # 时租付费超时
    HourlyTimeout = db.Column(db.Float)

    def __init__(self) -> None:
        super().__init__()
        self.Name = '測試車場'
        self.Brand = 'PyCarPark'
        self.Company = 'PyCarPark'
        self.Address = '請填寫聯係地址'
        self.Phone = '請填寫聯係電話'
        self.Model = "Standard"
        self.HourlyTimeout = 15.0

    def to_dict(self):
        """
        转换键值对
        """
        return dict([(c.name, getattr(self, c.name)) for c in self.__table__.columns])

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'Name': '車場名稱', 'Brand': '品牌名稱', 'Company': '管理公司','Address': '聯係地址', 'Phone': '聯係電話','HourlyTimeout':'付費超時','Model':'車場模式'}
        return ColumnName

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = CarParkSetting.query.first()
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                else:
                    return "ignore"
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")

    @staticmethod
    def table_init():
        """
        初始化
        """
        r = CarParkSetting.query.first()
        if not r:
            r = CarParkSetting()
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName}：初始化成功！")
